package com.zjt.web;

import com.zjt.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/report")
public class ReportFormController{



    /**
     * 导出报表
     * @return
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response){
        //获取数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",11);
        map.put("name","张三");
        map.put("sex","男");
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);

        //excel标题
        String[] title = {"年龄","名称","性别"};

        //excel文件名
        String fileName = "学生信息表"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "学生信息表";

        String[][] dataList = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            dataList[i] = new String[title.length];
            Map<String,Object> map1 = list.get(i);
            dataList[i] = new String[map1.size()];
            dataList[i][0] = map1.get("age").toString();
            dataList[i][1] = map1.get("name").toString();
            dataList[i][2] = map1.get("sex").toString();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, dataList, null);

        //响应到客户端
        try {
                this.setResponseHeader(response, fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
        } catch (Exception e) {
                e.printStackTrace();
            }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }}
